﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Skyworth.CRM.Common;
using Skyworth.CRM.Service.Entity;
using Skyworth.CRM.Service.IBLL;

namespace Skyworth.CRM.Web.Orders
{
    public partial class AddOrder : BasePage
    {
        protected int CustId = 0;
        protected int OrderId = 0;
        private static IOrdersBLL ordersBLL = IocContainer.Instance.Resolve<IOrdersBLL>();
        protected ICustCashBLL CustCashBll=IocContainer.Instance.Resolve<ICustCashBLL>();
        private ICustContactBLL custContactBLL = IocContainer.Instance.Resolve<ICustContactBLL>();
        private ICustDreeBLL dreeBll = IocContainer.Instance.Resolve<ICustDreeBLL>();
        private IStockBLL stockBLL = IocContainer.Instance.Resolve<IStockBLL>();
        private IBrandBLL brandBLL = IocContainer.Instance.Resolve<IBrandBLL>();
        private static IProductBLL productBLL = IocContainer.Instance.Resolve<IProductBLL>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CustId =IndividualId;
                if ("update" == Request.QueryString["Type"].ToString().ToLower())
                {
                    int.TryParse(Request.QueryString["Id"], out OrderId);
                    if (OrderId > 0)
                    {
                        DataTable orderDetail;
                        Order ordeEntity = ordersBLL.GetOrderById(OrderId, out orderDetail);
                        this.txtOrderName.Text = ordeEntity.OrderName;
                        this.txtDescription.Text = ordeEntity.Notes;
                        this.ddlAddress.SelectedValue = ordeEntity.CusDreeId.ToString();
                        this.ddlLinkPeople.SelectedValue = ordeEntity.ContactId.ToString();
                        this.ddlStock.SelectedValue = ordeEntity.StockId.ToString();
                        this.txtOrderNo.Text = ordeEntity.OrderCode;
                        this.orderDetailBody.Text = BuildOrderDetail(orderDetail);
                        this.txtTotalNumber.Text = ordeEntity.TotalNumber.ToString();
                        this.txtTotalVolume.Text = ordeEntity.TotalVolume.ToString();
                        this.txtTotalPrice.Text = ordeEntity.TotalPrice.ToString();
                        this.txtTotalTaxPrice.Text = ordeEntity.TotalTaxPrice.ToString();
                    }
                }
                else
                {
                    this.txtOrderNo.Text = "CSEO" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }

                BinDropDownList(this.ddlBrand, brandBLL.GetBrand("", null),"【请选择品牌】","-1");
                BuildDropDownList(CustId);

                CustCash cash = CustCashBll.GetCustomerCash(CustId);
                if (cash != null)
                {
                    this.txtTotalMoney.Text = cash.TotalAmount.ToString();
                    this.txtCredit.Text = cash.CreditAmount.ToString();
                    this.txtCashAmount.Text = cash.CashAmount.ToString();
                }
            }
        }

        private void BuildDropDownList(int custId)
        {
            DataTable dtContact = custContactBLL.Query(" FCustId=" + custId);
            BinDropDownList(this.ddlLinkPeople, dtContact, "", "");

            DataTable dtAddress = dreeBll.Query(" FCustId="+custId);
            BinDropDownList(this.ddlAddress,dtAddress,"","");

            DataTable dtStock = stockBLL.Query(" and FDeptId=" + custId + " and Ftype=1");
            BinDropDownList(this.ddlStock,dtStock,"","");

        }

        protected string BuildOrderDetail(DataTable orderDetail)
        {
            StringBuilder result = new StringBuilder();
            if(orderDetail!=null && orderDetail.Rows.Count>0)
            {
                foreach (DataRow row in orderDetail.Rows)
                {
                    result.Append("<tr>");
                    result.AppendFormat("<td>{0}</td>",row["FProductName"] );
                    result.AppendFormat("<td>{0}</td>", row["Fqty"]);
                    result.AppendFormat("<td>{0}</td>", row["Famount"]);
                    result.AppendFormat("<td>{0}</td>", row["Ftaxamount"]);
                    result.Append("<td><a href='javascript:void(0)' onclick='RemoveRow(this)'>移除</a></td>");
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["FUnitVolume"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fprice"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ftax"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ftaxprice"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Ffanli"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Funit"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fqtyvolume"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>", row["Fnote"]);
                    result.AppendFormat("<td style='display: none;'>{0}</td>",row["FProductId"]);
                    result.Append("</tr>");
                }
            }

            return result.ToString();
        }

        [WebMethod]
        public static string CreateOrder(string orderName, string orderNo,int custId,int dreeId,int stockId,int contactId,double totalNumber ,double totalVolume, decimal totalPrice,decimal totalTaxPrice, string notes,string json,Boolean isSubmit)
        {
            Order model = new Order();
            model.OrderName = orderName;
            model.ContactId =contactId;
            model.CustId = custId;
            model.CusDreeId = dreeId;
            model.StockId = stockId;
            model.Notes = notes;
            model.TotalPrice = totalPrice;
            model.TotalNumber = totalNumber;
            model.TotalVolume = totalVolume;
            model.TotalTaxPrice = totalTaxPrice;
            model.Creator = custId;
            model.OrderCode = orderNo;

            DataTable dt = SerializationHelper.Json2DataTable(json);

            return ordersBLL.AddOrder(model, dt, isSubmit);
        }

       [WebMethod]
        public static Boolean UpdateOrder(int orderId,string orderName, string orderNo, int custId, int dreeId, int stockId, int contactId, double totalNumber, double totalVolume, decimal totalPrice, decimal totalTaxPrice, string notes, string json,Boolean isSubmit)
       {
           Order model = new Order();
           model.OrderName = orderName;
           model.ContactId = contactId;
           model.CustId = custId;
           model.CusDreeId = dreeId;
           model.StockId = stockId;
           model.Notes = notes;
           model.TotalPrice = totalPrice;
           model.TotalNumber = totalNumber;
           model.TotalVolume = totalVolume;
           model.TotalTaxPrice = totalTaxPrice;
           model.Creator = custId;
           model.Id = orderId;
           model.OrderCode = orderNo;

           DataTable dt = SerializationHelper.Json2DataTable(json);

           return ordersBLL.UpdateOrder(model, dt,isSubmit);
       }

       [WebMethod]
       public static string GetProductsWithPrice(string productName, string brandId, string productTypeId, string orderField, string orderValue, int pageIndex, int pagePerSize, string custId, string productModel)
       {
           string strResult;
           IProductBLL productBLL = IocContainer.Instance.Resolve<IProductBLL>();
           StringBuilder strWhere = new StringBuilder(" where 1=1");
           if (!string.IsNullOrEmpty(productName))
           {
               strWhere.Append(" and ProductName like '%" + productName + "%'");
           }
           if (!string.IsNullOrEmpty(productModel))
           {
               strWhere.Append(" and ProductModel like '%" + productModel + "%'");
           }
           if (brandId != "-1")
           {
               strWhere.Append(" and brandId=" + brandId);
           }
           if (productTypeId != "-1")
           {
               strWhere.Append(" and ProductTypeId=" + productTypeId);
           }
           strWhere.Append(" and IsDisabled=0 ");

           StringBuilder strOrderBy = new StringBuilder(" Order by ");
           strOrderBy.Append(!string.IsNullOrEmpty(orderField) ? " " + orderField : "  ProductName  ");
           strOrderBy.Append(!string.IsNullOrEmpty(orderValue) ? " " + orderValue : "  asc ");

           int totalRecords = 0;
           int totalPages = 0;
           DataTable dtProducts = productBLL.GetProductsWithPriceByPage(strWhere.ToString(),custId,strOrderBy.ToString(), pageIndex, pagePerSize, out totalRecords,
                                          out totalPages);

           strResult = SerializationHelper.DataTable2Json(dtProducts);

           return "{\"totalRecords\":\"" + totalRecords.ToString() + "\" ,\"totalPages\":\"" + totalPages.ToString() + "\",\"rows\":" +
                  strResult + " }";

       }

    }
}
